// routes/file.js
const Router = require('koa-router');
const multer = require('koa-multer');
const path = require('path');
const db = require('../db');
const { uploadFile, getFileList, uploadFolderHandler } = require('../controllers/fileController');
const uploadDir = path.join(__dirname, '../uploads'); // 确保路径正确

// 创建目录（如果不存在）
const fs = require('fs');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}
// 文件存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir); // 使用绝对路径
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    cb(null, uniqueSuffix + '-' + file.originalname);
  }
});
const upload = multer({ storage });

const router = new Router({ prefix: '/api/file' });

// 上传接口
router.post('/upload', upload.single('file'), uploadFile);

// 批量上传文件夹接口
router.post('/upload-folder', upload.any(), uploadFolderHandler);

// 查询接口（带分页）
router.get('/list', async (ctx) => {
  const { page = 1, pageSize = 10, keyword = '', module = '' } = ctx.query;
  const offset = (page - 1) * pageSize;

  const whereClause = [];
  const params = [];

  if (keyword) {
    whereClause.push(`filename LIKE ?`);
    params.push(`%${keyword}%`);
  }
  if (module) {
    whereClause.push(`module_name LIKE ?`);
    params.push(`%${module}%`);
  }

  const whereSql = whereClause.length ? `WHERE ${whereClause.join(' AND ')}` : '';

  const [rows] = await db.query(
    `SELECT id, filename, relative_path, mime_type, module_name, created_at 
     FROM uploaded_files ${whereSql} 
     ORDER BY created_at DESC LIMIT ?, ?`,
    [...params, parseInt(offset), parseInt(pageSize)]
  );
console.log(rows,'rowsrowsrows',params);

  const [countResult] = await db.query(
    `SELECT COUNT(*) as total FROM uploaded_files ${whereSql}`,
    params
  );

  const baseUrl = `${ctx.protocol}://${ctx.host}/`;

  ctx.body = {
    code: 200,
    data: rows.map(item => ({
      ...item,
      url: baseUrl + encodeURIComponent(item.relative_path)
    })),
    pagination: {
      total: countResult[0].total,
      page: Number(page),
      pageSize: Number(pageSize)
    }
  };
});

// 查询详情接口
router.get('/detail/:id', async (ctx) => {
  const id = ctx.params.id;

  const [rows] = await db.query(
    `SELECT * FROM uploaded_files WHERE id = ?`,
    [id]
  );

  if (rows.length === 0) {
    ctx.body = { code: 404, message: '文件不存在' };
    return;
  }

  const item = rows[0];
  item.url = `${ctx.protocol}://${ctx.host}/${encodeURIComponent(item.relative_path)}`;
  ctx.body = { code: 200, data: item };
});

module.exports = router;
